#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>
#include <QPushButton>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("客户端");

    serverSocket = new QTcpSocket(this);

    serverSocket->connectToHost("127.0.0.1", 9090);

    this->connect(serverSocket, &QTcpSocket::readyRead, this, [=](){
        QString response = serverSocket->readAll();
        QString log = "服务器端说: "+response;

        ui->listWidget->addItem(log);
    });

    bool ret = serverSocket->waitForConnected();
    if(!ret)
    {
        QMessageBox::critical(this, "连接服务器错误", serverSocket->errorString());
        exit(1);
    }

    connect(ui->pushButton, &QPushButton::clicked, this, [=](){
        QString text = ui->lineEdit->text();

        serverSocket->write(text.toUtf8());

        QString log = "客户端说: "+text;

        ui->listWidget->addItem(log);

        ui->lineEdit->setText("");
    });
}

Widget::~Widget()
{
    delete ui;
}

